/**
 * 
 */
package com.mvc.controller.healthmanager;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.huangqj.consant.ValidatorUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.mvc.model.base.Json;
import com.mvc.model.healthmanager.archive.Eye;
import com.mvc.model.healthmanager.archive.Listen;
import com.mvc.service.healthmanager.ListenServiceI;

/**
 * 听力信息处理控制器
 * @author qingjie
 *
 */
@RequestMapping("/listen")
@Controller
public class ListenController {
	@Autowired
	private ListenServiceI lsi;
	
	@RequestMapping("/saveListen")
	@ResponseBody
	public Json saveListen(HttpServletRequest request,Listen listen) throws UnsupportedEncodingException{
		String json = request.getParameter("json");
		System.out.println("未转化数据：" + json);
//		json = URLDecoder.decode(json, "utf-8");
		String[] s = json.split("=");
		if (s.length > 1) {
			json = s[1];
		}
		Listen l = new Listen();
		if (!json.isEmpty()) {
			l = JSON.parseObject(json, Listen.class);
			l.setId(null);
		}
		listen = lsi.saveOrUpdate(l);
		Json j = new Json();
		if(listen!=null&&!json.isEmpty()){
			j.setMsg("保存成功");
			j.setSuccess(true);
			j.setObj(listen);
		}else{
			j.setMsg("保存失败");
			j.setSuccess(false);
		}
		return j;
	}
	
	@RequestMapping(value="/saveListen", method=RequestMethod.POST,consumes = "application/json")
	@ResponseBody
	public Json saveListen(@RequestBody List<Listen> ls,HttpServletRequest request) throws Exception{
		System.out.println("未转化的数据："+JSON.toJSONString(ls));
		List<Listen> list = new ArrayList<Listen>();
		Json j = new Json();
		if(ls.size()>0){
			for(Listen l : ls){
				Long appLocalId = ValidatorUtil.isNullOnLong(l.getId())?null:l.getId();
				l.setId(null);
				Listen listen = new Listen();
				listen = lsi.saveOrUpdate(l);
				if(listen!=null&&!ValidatorUtil.isNullOnLong(listen.getId())){
					listen.setRespCode(0);
				}else{
					listen.setRespCode(-1);
				}
				listen.setAppLocalId(appLocalId);
				list.add(listen);
			}
			j.setMsg("数据已处理");
			j.setSuccess(true);
			j.setObj(list);
		}else{
			j.setMsg("数据为空");
			j.setSuccess(false);
		}
		return j;
	}
}
